package com.qiaofang.housewarehouse.dao.impl;

import com.qiaofang.housewarehouse.base.util.ArraySelfUtils;
import com.qiaofang.housewarehouse.dao.ESSearchHouseDao;
import com.qiaofang.housewarehouse.dao.elasticsearch.EsClient;
import com.qiaofang.housewarehouse.stub.bean.HousingAcqAttentionDTO;
import com.qiaofang.housewarehouse.stub.constants.HouseTypeEnum;
import io.netty.util.internal.StringUtil;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @Author: GJ
 * @Date: 2018/4/10 19:26
 * @Description:
 */
@Repository
public class ESSearchHouseDaoImpl implements ESSearchHouseDao {
    private static final Logger logger = LoggerFactory.getLogger(ESSearchHouseDaoImpl.class);

    @Override
    public SearchResponse searchHouseList(Map<String, String> paramMap, List<HousingAcqAttentionDTO> housingAcqAttentionDTOS, String type) throws Exception {
        int offset = 0;
        int size = 50;
        if (!StringUtil.isNullOrEmpty(paramMap.get("pageSize"))) {
            size = Integer.valueOf(paramMap.get("pageSize"));
        }
        if (!StringUtil.isNullOrEmpty(paramMap.get("pageIndex"))) {
            offset = (Integer.valueOf(paramMap.get("pageIndex")) - 1) * size;
        }
       // QueryBuilder queryBuilder = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if ("sell".equals(type)) {
            if(housingAcqAttentionDTOS != null && housingAcqAttentionDTOS.size() > 0){
                housingAcqAttentionDTOS.forEach(sell->{
                    QueryBuilder queryBuilder = QueryBuilders.boolQuery();
                    queryBuilder = this.paramCondition(paramMap, queryBuilder);
                    WildcardQueryBuilder estate = QueryBuilders.wildcardQuery("estate", "*" + sell.getEstateName() + "*");
                    RangeQueryBuilder sellPrice = null;
//                    if(sell.getSellPriceMin() != null || sell.getSellPriceMax() != null){
//                        sellPrice = QueryBuilders.rangeQuery("sellPriceR").gte(sell.getSellPriceMin()).lte(sell.getSellPriceMax());
//                    }
                    if (sellPrice != null){
                        ((BoolQueryBuilder) queryBuilder).must(estate).must(sellPrice);
                    }else{
                        ((BoolQueryBuilder) queryBuilder).must(estate);
                    }
                    boolQueryBuilder.should(queryBuilder);
                });
            }
        }
        if ("rent".equals(type)) {
            if(housingAcqAttentionDTOS != null && housingAcqAttentionDTOS.size() > 0){
                housingAcqAttentionDTOS.forEach(rent->{
                    QueryBuilder queryBuilder = QueryBuilders.boolQuery();
                    queryBuilder = this.paramCondition(paramMap, queryBuilder);
                    WildcardQueryBuilder estate = QueryBuilders.wildcardQuery("estate", "*" + rent.getEstateName() + "*");
                    RangeQueryBuilder rentPrice = null;
//                    if(rent.getRentPriceMax() != null || rent.getRentPriceMin() != null){
//                         rentPrice = QueryBuilders.rangeQuery("rentPriceR").gte(rent.getRentPriceMin()).lte(rent.getRentPriceMax());
//                    }
                    if(rentPrice != null){
                        ((BoolQueryBuilder) queryBuilder).must(estate).must(rentPrice);
                    }else{
                        ((BoolQueryBuilder) queryBuilder).must(estate);
                    }
                    boolQueryBuilder.should(queryBuilder);
                });
            }

        }
        if(housingAcqAttentionDTOS == null || (housingAcqAttentionDTOS!= null && housingAcqAttentionDTOS.isEmpty())){
            QueryBuilder queryBuilder = QueryBuilders.boolQuery();
            queryBuilder = this.paramCondition(paramMap, queryBuilder);
            boolQueryBuilder.should(queryBuilder);
        }

        logger.info("查询语句为：{}", boolQueryBuilder.toString());
        SearchResponse searchResponse = EsClient.queryData(paramMap.get("indexName"), paramMap.get("typeName"), boolQueryBuilder, offset, size);
        return searchResponse;
    }

    private QueryBuilder paramCondition(Map<String, String> paramMap,QueryBuilder queryBuilder){
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringUtil.isNullOrEmpty(value) || "pageSize".equals(key) || "pageIndex".equals(key) || "indexName".equals(key) || "typeName".equals(key)) {
                continue;
            }
            Float floatEnd = Float.valueOf("999999999");
            Integer integerEnd = Integer.valueOf("999999999");
            if ("rentPriceRange".equals(key)) {
                String[] split = value.split("~");
                Float start = Float.valueOf(split[0]);
                Float end = Float.valueOf(split[1]);
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("rentPriceR").gte(start).lte((end != 0) ? end : floatEnd));
            } else if ("sellPriceRange".equals(key)) {
                String[] split = value.split("~");
                Float start = Float.valueOf(split[0]);
                Float end = Float.valueOf(split[1]);
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("sellPriceR").gte(start).lte((end != 0) ? end : floatEnd));
            } else if ("roomAreaRange".equals(key)) {
                String[] split = value.split("~");
                Float start = Float.valueOf(split[0]);
                Float end = Float.valueOf(split[1]);
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("roomAreaR").gte(start).lte((end != 0) ? end : floatEnd));
            } else if ("yearRange".equals(key)) {
                String[] split = value.split("~");
                Integer start = Integer.valueOf(split[0]);
                Integer end = Integer.valueOf(split[1]);
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("yearR").gte(start).lte((end != 0) ? end : integerEnd));
            } else if ("floorRange".equals(key)) {
                String[] split = value.split("~");
                Integer start = Integer.valueOf(split[0]);
                Integer end = Integer.valueOf(split[1]);
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("floorR").gte(start).lte((end != 0) ? end : integerEnd));
            } else if ("houseType".equals(key)) {
                Float houseType = Float.valueOf(value);
                if (houseType.equals(Float.valueOf(HouseTypeEnum.FIVE.getValue()))) {
                    ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("houseTypeR").gte(houseType));
                } else {
                    ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.termQuery("houseTypeR", houseType));
                }
            } else if ("keywords".equals(key)) {
                //        ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.wildcardQuery("estate", "*" + value + "*"));
            } else if ("contactMobiles".equals(key)) {
               /* String[] values = value.split(",");
                Object[] subAry = ArraySelfUtils.splitAry(values, 1024);
                for (Object obj : subAry) {
                    String[] aryItem = (String[]) obj;
                    ((BoolQueryBuilder) queryBuilder).mustNot(QueryBuilders.termsQuery("contactMobile", aryItem));
                }*/
            }else if("collectionTime".equals(key)){
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("publishTime").lte(value));
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.rangeQuery("createTime").lte(value));
            }  else {
                ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.wildcardQuery(key, "*" + value + "*"));
            }
        }
        return queryBuilder;
    }
}
